package qlsl.androiddesign.api.util.other;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;

import com.itheima.pulltorefreshlib.PullToRefreshScrollView;

import java.io.File;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import qlsl.androiddesign.api.activity.baseactivity.FunctionActivity;
import qlsl.androiddesign.api.activity.commonactivity.PhotoUpdateActivity;
import qlsl.androiddesign.api.constant.Constant;
import qlsl.androiddesign.api.library.email.MultiMailsender;
import qlsl.androiddesign.api.util.commonutil.DensityUtils;
import qlsl.androiddesign.api.util.commonutil.Log;
import qlsl.androiddesign.api.util.commonutil.ScreenUtils;
import qlsl.androiddesign.api.util.commonutil.TDevice;
import qlsl.androiddesign.api.view.commonview.ListViewNeedAdapterDialog;

/**
 * 类描述：公共代码可以放置此处，方便其他Activity调用
 * 需要传入的键：****
 * 传入的值类型：****
 * 传入的值含义：****
 * 是否必传：****
 * 作者：郑朝军 on 2017/6/14 11:29
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2017/6/14 11:29
 * 修改备注：
 */
public class Utils
{
    private static class UtilHodel
    {
        public static final Utils UTIL = new Utils();
    }

    public static Utils getInstance()
    {
        return UtilHodel.UTIL;
    }


    public ListViewNeedAdapterDialog showQuickOption(Activity activity,
                                                     BaseAdapter adapter)
    {
        ListViewNeedAdapterDialog dialog = new ListViewNeedAdapterDialog(
                activity, adapter);
        // Dialog宽度设置和ListView高度设置
        dialog.setDialogWidth((int) ((int) ScreenUtils.getScreenWidth(activity) * 0.7));
        // dialog.setListHeight(DensityUtils.dip2px(activity, 10));
        // dialog.setType(Type.BOTTOM);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        return dialog;
    }

    public ListViewNeedAdapterDialog showQuickOption(Activity activity, BaseAdapter adapter, int
            ListHeight, int dialogWidth, ListViewNeedAdapterDialog.Type type)
    {
        ListViewNeedAdapterDialog dialog = new ListViewNeedAdapterDialog(
                activity, adapter);
        // Dialog宽度设置和ListView高度设置
        if (dialogWidth != 0)
        {
            dialog.setDialogWidth(dialogWidth);
        }
        else
        {
            dialog.setDialogWidth((int) ((int) ScreenUtils
                    .getScreenWidth(activity) * 0.7));
        }

        if (ListHeight != 0)
        {
            dialog.setListHeight(DensityUtils.dip2px(activity, ListHeight));
        }
        if (type != null)
        {
            dialog.setType(type);
        }

        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        return dialog;
    }


    /**
     * 获取上个界面返回过来的信息<br/>
     */
    public Serializable getItem(Activity activity)
    {
        return activity.getIntent().getSerializableExtra("data");
    }

    /**
     * 获取上个界面返回过来的信息<br/>
     */
    public Serializable getItemForKey(Activity activity, String key)
    {

        if (key == null || TextUtils.isEmpty(key))
            return null;
        return activity.getIntent().getSerializableExtra(key);
    }

    /**
     * 获取上个界面返回过来的信息<br/>
     */
    public int getIntForKey(Activity activity, String key, int defaultValue)
    {
        if (key == null || TextUtils.isEmpty(key))
            return -1;
        return activity.getIntent().getIntExtra(key, defaultValue);
    }

    /**
     * 获取Bundle
     *
     * @param activity
     * @return
     */
    public Bundle getItemGetBundle(Activity activity)
    {
        return activity.getIntent().getBundleExtra("data");
    }

    /**
     * 获取Bundle
     *
     * @param activity
     * @return
     */
    public Bundle getItemGetBundle(Activity activity, String bundleKey)
    {
        return activity.getIntent().getBundleExtra(bundleKey);
    }

    /**
     * 通过拿到Bundle在拿到Serializable<br/>
     * 通过Bundle传递的数据的
     *
     * @param activity
     * @return
     */
    public Serializable getItemToBundle(Activity activity, String key)
    {
        Bundle bundle = getItemGetBundle(activity);
        if (bundle != null)
            return bundle.getSerializable(key);
        else
            return null;
    }

    /**
     * 通过拿到Bundle在拿到Serializable<br/>
     * 通过Bundle传递的数据的
     *
     * @param activity
     * @return
     */
    public Serializable getItemToBundle(Activity activity, String bundleKey,
                                        String key)
    {
        Bundle bundle = getItemGetBundle(activity, bundleKey);
        if (bundle != null)
            return bundle.getSerializable(key);
        else
            return null;
    }

    /*
     * 跳转到编辑页面
     */
    public void startActivityToEditActivity(Activity activity,
                                            ListView listView, int position, int maxLength)
    {
//        HashMap<String, Object> map = (HashMap<String, Object>) listView
//                .getAdapter().getItem(position);
//        String text = (String) map.get("text");
//        String value = (String) map.get("value");
//
//        Intent intent = new Intent(activity, EditActivity.class);
//        intent.putExtra("title", "编辑" + text);
//
//        intent.putExtra("maxLength", maxLength == 0 ? 16 : maxLength);
//        intent.putExtra("content", value);
//
//        activity.startActivityForResult(intent, 0);
    }

    public void startActivityToPhotoUpdateActivity(Activity activity,
                                                   List<String> urls, int max_count, int
                                                           position)
    {
        Intent intent = new Intent(activity, PhotoUpdateActivity.class);
        intent.putExtra("urls", (Serializable) urls);
        intent.putExtra("max_count", max_count);
        activity.startActivityForResult(intent, position);
    }


    public void sendURIFileToEmail(Activity activity, Uri uri)
    {
        String deviceName = "选择视频中出错的问题：" + "uri===" + uri;
        String msg = "deviceName===" + deviceName + "===uri===" + uri;
        Log.recordLogError("zcj", msg);

        sendReportFileToEmail(deviceName,
                new WeakReference<Activity>(activity).get());
    }

    /**
     * 后台发送含附件(Log日志)的邮件<br/>
     */
    public void sendLogFileToEmail(final File file, final String name,
                                   final String email, final String title, final String content)
    {
        new Thread()
        {
            public void run()
            {
                Log.i("mail", "正在发送邮件：Log日志<br/>文件：" + file);
                MultiMailsender.MultiMailSenderInfo mailInfo = new MultiMailsender
                        .MultiMailSenderInfo();
                mailInfo.setMailServerHost("smtp.qq.com");
                mailInfo.setMailServerPort("25");
                mailInfo.setValidate(true);
                mailInfo.setUserName("3301436616@qq.com");
                mailInfo.setPassword("cunonzupwfgscida");
                mailInfo.setFromAddress("3301436616@qq.com");
                mailInfo.setToAddress(email);
                mailInfo.setSubject("Log日志-" + name + "-" + title);
                mailInfo.setContent(content);
                mailInfo.setFiles(new File[]{file});
                MultiMailsender mailSender = new MultiMailsender();
                mailSender.sendMailtoMultiReceiver(mailInfo);

            }

            ;
        }.start();

    }

    /**
     * 发送log日志
     *
     * @param deviceName
     * @param context
     */
    public void sendReportFileToEmail(final String deviceName,
                                      final Context context)
    {
        new Thread()
        {
            public void run()
            {
                MultiMailsender.MultiMailSenderInfo mailInfo = new MultiMailsender
                        .MultiMailSenderInfo();

                mailInfo.setMailServerHost("smtp.163.com");// 网易邮箱:
                // SMTP服务器：smtp.163.com
                // （端口号25）

                mailInfo.setMailServerPort("25");
                mailInfo.setValidate(true);

                mailInfo.setUserName("15771040695@163.com");
                mailInfo.setPassword("zxylovewl1234");

                mailInfo.setFromAddress("15771040695@163.com");
                mailInfo.setToAddress("2939143482@qq.com");

                mailInfo.setSubject("异常报告-" + TDevice.getAppName(context)
                        + "-v" + TDevice.getVersionName());

                mailInfo.setContent(deviceName + "-" + Constant.address + "("
                        + Constant.latitude + "," + Constant.longitude + ")");
                mailInfo.setFiles(new File[]{new File(Log.getLogPath(context))});
                String[] receivers = new String[]{"1250393285@qq.com"};
                mailInfo.setReceivers(receivers);
                mailInfo.setCcs(receivers);
                MultiMailsender mailSender = new MultiMailsender();
                mailSender.sendMailtoMultiReceiver(mailInfo);
            }

            ;
        }.start();

    }

/////////////////////////////////应用层////////////////////////////////////////////////////////////////

    public ArrayList<HashMap<String, String>> createRoundSearchData()
    {
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        String[] names = new String[]{"50", "100", "150", "200"};
        for (int index = 0; index < names.length; index++)
        {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("text", names[index]);
            list.add(map);
        }
        return list;
    }

    /**
     * 滑动到底部
     *
     * @param refreshView
     */
    public static void refreshScrollViewScrollBottom(final FunctionActivity activity, final
    PullToRefreshScrollView refreshView)
    {
        refreshView.getRefreshableView().post(new Runnable()
        {
            public void run()
            {
                activity.hideSoftInput();
                refreshView.getRefreshableView().fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    /**
     * 滑动到顶部
     *
     * @param refreshView
     */
    public static void refreshScrollViewScrollTop(final PullToRefreshScrollView refreshView)
    {
        refreshView.getRefreshableView().post(new Runnable()
        {
            public void run()
            {
                refreshView.getRefreshableView().fullScroll(ScrollView.FOCUS_UP);
            }
        });
    }

    /**
     * 滑动到指定位置
     *
     * @param refreshView
     * @param recyclerView
     * @param position     位置从1开始
     */
    public static void refreshScrollViewScrollPosition(final PullToRefreshScrollView refreshView,
                                                       final RecyclerView recyclerView, final int
                                                               position)
    {
        final float positionHeight = (float) ((position == 0 ? 0 :
                (recyclerView.getAdapter().getItemCount() == position ? position : position - 1)) *
                ((recyclerView.getChildAt(0).getHeight() + 0.1)));
        refreshView.getRefreshableView().post(new Runnable()
        {
            public void run()
            {
                refreshView.getRefreshableView().smoothScrollTo(0, (int) positionHeight);
            }
        });
    }
}
